package com.berwin.syncer.network;

import com.alibaba.fastjson.JSONObject;
import com.berwin.syncer.listener.SocketEventListener;

import java.io.*;
import java.net.Socket;

public class Session implements Runnable {

    public static final int MSG_TYPE_SYNC_DEVICE = 0; // 同步设备名消息
    public static final int MSG_TYPE_SYNC_TEXT = 1; // 同步文本消息
    public static final int MSG_TYPE_SYNC_TEXTS = 2; // 同步所有文本消息
    public static final int MSG_TYPE_SYNC_FILE = 3; // 同步文件消息
    public static final int MSG_TYPE_SYNC_FILES = 5; // 同步所有文件消息
    public static final int MSG_TYPE_CONNECT = 10; // 连接消息
    public static final int MSG_TYPE_DISCONNECT = 11; // 断开连接消息

    private Socket socket;
    private SocketEventListener listener;
    private boolean isRunning;
    private String device = "UNKNOWN";

    public Session(Socket socket, SocketEventListener listener) {
        this.socket = socket;
        this.listener = listener;
    }

    @Override
    public void run() {
        while (this.isRunning) {
            try {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String dataStr = bufferedReader.readLine();
                if (dataStr == null)
                    break;
                System.out.println(dataStr);
                JSONObject obj = JSONObject.parseObject(dataStr);
                if (obj.getInteger("type") == MSG_TYPE_SYNC_DEVICE) {
                    this.device = obj.getString("device");
                    this.listener.onConnect(this);
                    continue;
                }
                listener.onMessage(this, obj);
            } catch (Exception e) {
//                System.out.println("客户端断开连接");
//                e.printStackTrace();
                this.isRunning = false;
            }
        }
        this.listener.onDisconnect(this);
        try {
            this.socket.close();
            this.socket = null;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        this.isRunning = true;
        new Thread(this).start();
    }

    public void stop() {
        if (this.socket != null) {
            try {
                this.socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public String getDevice() {
        return this.device;
    }

    public void send(String message) {
        if (!this.isRunning || this.socket == null)
            return;
        try {
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            bufferedWriter.write(message + "\n");
            bufferedWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Socket getSocket() {
        return this.socket;
    }
}
